package com.myway.core.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by yufei on 2017/12/15.
 */
@Slf4j
public class LoginFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
//        TabMemberInfo sysUser = (TabMemberInfo) req.getSession().getAttribute("user");
        if(req.getSession().getAttribute("userType") == null){
            String path1 = req.getServletPath();
            String str = path1.split("/")[2];
            System.out.println("getServletPath:\t" + path1);
            String path = "/" + str + "/login";
            //resp.sendRedirect(path);
            //跳转到登录页面，把用户请求的url作为参数传递给登录页面。
            ((HttpServletResponse) servletResponse).sendRedirect(path+"?redirect=" + ((HttpServletRequest) servletRequest).getRequestURL());
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    public void destroy() {

    }
}
